package cn.esbot.wx.mp.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class JsoupUtils {
    /**
     * 判断文本总是否含有媒体文件链接
     *
     * @param text 待判断的文本
     * @return 是否含有链接
     */
    public static boolean existMediaLink(String text) {
        if (!StringUtils.hasText(text)) {
            return false;
        }
        if (text.contains("src") && (text.contains("img") || text.contains("video"))) {
            Document document = Jsoup.parseBodyFragment(text);
            Elements elements = document.getElementsByAttribute("src");
            return elements.size() > 0;
        }
        return false;
    }

    /**
     * 提取文本中的媒体链接
     *
     * @param text 待提取链接的文本
     * @return 包含有提取到的链接列表
     */
    public static List<String> extraMediaLink(String text) {
        List<String> mediaLinks = new ArrayList<>();
        if (StringUtils.hasText(text) && text.contains("src") && (text.contains("img") || text.contains("video"))) {
            Document document = Jsoup.parseBodyFragment(text);
            Elements elements = document.getElementsByAttribute("src");
            elements.parallelStream().forEach(element -> {
                System.out.println(element.toString());
                mediaLinks.add(element.attr("src"));
            });
        }
        return mediaLinks;
    }

    public static List<String> extraImageLink(String text) {
        List<String> imageLinks = new ArrayList<>();
        if (StringUtils.hasText(text) && text.contains("src") && (text.contains("img"))) {
            Document document = Jsoup.parseBodyFragment(text);
            Elements imgElements = document.getElementsByTag("img");

            imgElements.parallelStream().forEach(element -> {
                if (element.hasAttr("src")) {
                    imageLinks.add(element.attr("src"));
                }
            });

        }
        return imageLinks;
    }

    public static List<String> extraVideoLink(String text) {
        List<String> videoLinks = new ArrayList<>();
        if (StringUtils.hasText(text) && text.contains("src") && (text.contains("video"))) {
            Document document = Jsoup.parseBodyFragment(text);
            Elements imgElements = document.getElementsByTag("video");

            imgElements.parallelStream().forEach(element -> {
                if (element.hasAttr("src")) {
                    videoLinks.add(element.attr("src"));
                }
            });

        }
        return videoLinks;
    }

}
